
//HAL

//BSP
//OS
#include <jxos_config.h>
#include "kernel/jxos_task.h"
#include "kernel/jxos_event.h"
#include "kernel/jxos_msg.h"
//LIB
#include "lib/bit.h"
#include "debug_print_task.h"


#if ((JXOS_TASK_ENABLE == 1)&&(JXOS_SYS_SERVICE_POWER_MGR_TASK_ENABLE == 1))
//SYS
void (*sys_power_mgr_task_hal_init_callback)(void) = 0;
void (*sys_power_mgr_task_prepare_to_sleep_callback)(void) = 0;
void (*sys_power_mgr_task_go_to_sleep_callback)(void) = 0;
void (*sys_power_mgr_task_recover_to_wake_callback)(void) = 0;

/***********************************************************/
static uint32_t power_mgr_keep_wake_mark = 0;
uint8_t power_mgr_interrupt_happened = 0;
static void sys_power_mgr_task(uint8_t task_id, void * parameter)
{
	if(
	#if(JXOS_ENENT_ENABLE == 1)
	(jxos_event_check_empty_all() == 1)&&
	#endif
	#if(JXOS_MSG_ENABLE == 1)
	(jxos_msg_check_empty_all() == 1)&&
	#endif
	(power_mgr_keep_wake_mark == 0))
	{
		if(sys_power_mgr_task_prepare_to_sleep_callback != 0){
			sys_power_mgr_task_prepare_to_sleep_callback();
		}

        if(power_mgr_interrupt_happened == 0){
			if(sys_power_mgr_task_go_to_sleep_callback != 0){
				sys_power_mgr_task_go_to_sleep_callback();
			}
        }
        else{
            power_mgr_interrupt_happened = 0;
        }
		
		if(sys_power_mgr_task_recover_to_wake_callback != 0){
			sys_power_mgr_task_recover_to_wake_callback();
		}
	}
}

void sys_power_mgr_task_init(void)
{
	//HAL
	if(sys_power_mgr_task_hal_init_callback != 0){
		sys_power_mgr_task_hal_init_callback();
	}
	//BSP

	//OS
	jxos_task_create(sys_power_mgr_task, "pwmgr_t", 0);

	//LIB

	//SYS TASK
}

/***********************************************************/
//public interface
static uint8_t keep_wake_mark_id = 0;
uint8_t sys_power_mgr_task_keep_wake_mark_get_id(void)
{
	if(keep_wake_mark_id < 32){
		return keep_wake_mark_id++;
	}
	else{
		sys_debug_print_task_sys_ser_print_str("keep_wake_mark_get_id error");
		return 0xff;
	}
}

void sys_power_mgr_task_keep_wake_mark_set(uint8_t mark_id)
{
	set_bit(power_mgr_keep_wake_mark, mark_id);
}

void sys_power_mgr_task_keep_wake_mark_reset(uint8_t mark_id)
{
	reset_bit(power_mgr_keep_wake_mark, mark_id);
}

void sys_power_mgr_task_interrupt_happened_falg(void)
{
    power_mgr_interrupt_happened = 1;
}

#endif
